﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using QXBook.Model;
using System.Data.Common;
using System.Data.SqlClient;
using System.Data;
using QXBook.Utils;
using System.Web;
using System.Configuration;

namespace QXBook.Service
{
    /// <summary>
    /// 购物车的操作方法
    /// </summary>
    public class ShoppingCartService : ServiceBase
    {
        /// <summary>
        /// 加入购物车
        /// </summary>
        /// <param name="user"></param>
        /// <param name="product"></param>
        public int InsertToCart(UsersInfo user, ProductInfo product)
        {
            //if (user == null) return 0;
            if (product == null) return 0;

            _cartcookie = Cookie.Get(ConfigurationManager.AppSettings["TokenCookieName"]);
            if (_cartcookie == null)
            {
                Guid gid = Guid.NewGuid();
                string token = gid.ToString();
                _cartcookie = Cookie.Set(ConfigurationManager.AppSettings["TokenCookieName"]);
                _cartcookie.Values["Token"] = token;
            }

            Cookie.Save(_cartcookie);

            ShoppingCartInfo cart = null;

            List<ShoppingCartInfo> list = this.GetShoppingCartByToken(product);
            if (list.Count > 0)
                cart = list[0];
            DbCommand cmd = new SqlCommand();
            int nTotal = 0;
            if (cart == null)
            {
                nTotal = 1;
                cmd.CommandText = "INSERT INTO ShoppingCart(Token,UserID,ProductID,ProductName,Price,Count) VALUES(@Token,0,@ProductID,@ProductName,@Price,@Count)";

            }
            else
            {
                nTotal = cart.Count + 1;
                cmd.CommandText = "UPDATE ShoppingCart SET UserID=@UserID,ProductID=@ProductID,ProductName=@ProductName,Price=@Price,Count=@Count WHERE Token=@Token";
            }

            base.db.AddInParameter(cmd, "@UserID", DbType.String, user != null ? user.UserID : 0);
            base.db.AddInParameter(cmd, "@Token", DbType.String, _cartcookie.Values["Token"]);
            base.db.AddInParameter(cmd, "@ProductID", DbType.Int32, product.ProductID);
            base.db.AddInParameter(cmd, "@ProductName", DbType.String, product.Title);
            base.db.AddInParameter(cmd, "@Price", DbType.Decimal, product.Price);
            base.db.AddInParameter(cmd, "@Count", DbType.Int32, nTotal);
            base.db.ExecuteNonQuery(cmd);

            return nTotal;
        }
        /// <summary>
        /// 登陆时更新购物车
        /// </summary>
        /// <param name="userID"></param>
        public void UpdateShoppingCart(int userID)
        {
            _cartcookie = Cookie.Get(ConfigurationManager.AppSettings["TokenCookieName"]);

            if (_cartcookie == null)
                return;
            DbCommand cmd = new SqlCommand();
            cmd.CommandText = "UPDATE ShoppingCart SET UserID=@UserID WHERE Token=@Token AND UserID=0";

            base.db.AddInParameter(cmd, "@UserID", DbType.Int32, userID);
            base.db.AddInParameter(cmd, "@Token", DbType.String, _cartcookie.Values["Token"]);
            base.db.ExecuteNonQuery(cmd);
        }

        /// <summary>
        /// 更新购物车数量
        /// </summary>
        /// <param name="cartID"></param>
        /// <param name="count"></param>
        public void UpdateShoppingCartCount(int cartID, int count)
        {
            DbCommand cmd = new SqlCommand();
            cmd.CommandText = "UPDATE ShoppingCart SET Count=@Count WHERE CartID=@CartID";

            base.db.AddInParameter(cmd, "@CartID", DbType.Int32, cartID);
            base.db.AddInParameter(cmd, "@Count", DbType.Int32, count);
            base.db.ExecuteNonQuery(cmd);
        }

        /// <summary>
        /// 创建订单
        /// 删除cookie
        /// </summary>
        /// <param name="user"></param>
        /// <param name="cart"></param>
        public void CreateOrder(UsersInfo user, OrderHeaderInfo orderHeader)
        {
            if (user == null) return;

            List<ShoppingCartInfo> carts = GetShoppingCartsForUser(user);

            List<OrderItemInfo> orderitems = new List<OrderItemInfo>();

            foreach (ShoppingCartInfo cart in carts)
            {
                OrderItemInfo item = new OrderItemInfo();
                item.ProductID = cart.ProductID;
                item.Count = cart.Count;
                item.Price = cart.Price;
                orderitems.Add(item);
            }

            int nTotal = ServiceFactory.CreateInstance<OrderService>().CreateOrder(orderHeader, orderitems);

            if (nTotal > 0)
            {
                this.Delete();
                _cartcookie = Cookie.Get(ConfigurationManager.AppSettings["TokenCookieName"]);
                if (_cartcookie != null)
                {
                    Cookie.Remove(this._cartcookie);
                }
            }
        }
        /// <summary>
        /// 通过Token和商品获取一条购物车信息,或者获取改token的购物车信息
        /// </summary>
        /// <param name="product"></param>
        /// <returns></returns>
        public List<ShoppingCartInfo> GetShoppingCartByToken(ProductInfo product)
        {
            List<ShoppingCartInfo> list = new List<ShoppingCartInfo>();
            _cartcookie = Cookie.Get(ConfigurationManager.AppSettings["TokenCookieName"]);
            if (_cartcookie != null)
            {
                DbCommand cmd = new SqlCommand();
                string sql = "SELECT CartID,Token,UserID,ProductID,ProductName,Price,Count FROM ShoppingCart WHERE Token='" + _cartcookie["Token"] + "'";
                if (product != null)
                {
                    sql += " AND ProductID=" + product.ProductID;
                }
                cmd.CommandText = sql;
                DataSet ds = this.db.ExecuteDataSet(cmd);

                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        ShoppingCartInfo shopping = new ShoppingCartInfo();
                        shopping.CartID = CommonUtils.ToInt(dr["CartID"]);
                        shopping.Token = CommonUtils.ToString(dr["Token"]);
                        shopping.UserID = CommonUtils.ToInt(dr["UserID"]);
                        shopping.ProductID = CommonUtils.ToInt(dr["ProductID"]);
                        shopping.ProductName = CommonUtils.ToString(dr["ProductName"]);
                        shopping.Price = CommonUtils.ToInt(dr["Price"]);
                        shopping.Count = CommonUtils.ToInt(dr["Count"]);
                        list.Add(shopping);
                    }
                }
            }

            return list;
        }

        /// <summary>
        /// 获取某个人的购物车信息
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public List<ShoppingCartInfo> GetShoppingCartsForUser(UsersInfo user)
        {
            List<ShoppingCartInfo> list = new List<ShoppingCartInfo>();

            DbCommand cmd = new SqlCommand();
            string sql = "SELECT CartID,UserID,ProductID,ProductName,Price,Count FROM ShoppingCart WHERE UserID=" + user.UserID;

            cmd.CommandText = sql;
            DataSet ds = this.db.ExecuteDataSet(cmd);

            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    ShoppingCartInfo shopping = new ShoppingCartInfo();
                    shopping.CartID = CommonUtils.ToInt(dr["CartID"]);
                    shopping.UserID = CommonUtils.ToInt(dr["UserID"]);
                    shopping.ProductID = CommonUtils.ToInt(dr["ProductID"]);
                    shopping.ProductName = CommonUtils.ToString(dr["ProductName"]);
                    shopping.Price = CommonUtils.ToInt(dr["Price"]);
                    shopping.Count = CommonUtils.ToInt(dr["Count"]);
                    list.Add(shopping);
                }
            }

            return list;
        }
        /// <summary>
        /// 创建订单后，删除购物车信息
        /// </summary>
        private void Delete()
        {
            if (_cartcookie != null)
            {
                string sql = "DELETE FROM ShoppingCart WHERE Token=" + _cartcookie["Token"];
                base.db.ExecuteNonQuery(sql);
            }
        }

        private System.Web.HttpCookie _cartcookie = null;
    }
}
